//
//  YYHomeViewController.m
//  YYWeather
//
//  Created by 姚英 on 16/7/4.
//  Copyright © 2016年 yy. All rights reserved.
//

#import "YYHomeViewController.h"
#import "XYCustomProgressView.h"

#import "YYHttpTool.h"
#import "XMLDictionary.h"
#import <MJExtension.h>
#import <MJRefresh.h>
#import "YYWeatherModel.h"
#import "YYForecastModel.h"
#import "YYForecastWeather.h"
#import "YYAlarmModel.h"

#import "YYNoHighlightButton.h"
#import "YYCityViewController.h"
#import "SQLOperation.h"

#import <SVProgressHUD/SVProgressHUD.h>

//#import "YYCityController.h"

@interface YYHomeViewController () <NSXMLParserDelegate, UIScrollViewDelegate>


@property (weak, nonatomic)  UIView *bkView;
@property (weak, nonatomic)  UIScrollView *scrollView;
//@property (weak, nonatomic)  UIButton *cityBtn;

/// 蒙版
@property(nonatomic, weak) UIView *maskView;
/// 渐变圆环
@property (nonatomic, strong) XYCustomProgressView *progress;
/// _nubLable
@property(nonatomic, weak) UILabel *nubLabel;

/// 当前的PM25值
@property(nonatomic, assign) int currentPM25;

/// 用于保存当前的 Element.
@property(nonatomic, strong) NSString *currentElementKey;

/// 用于保存
@property(nonatomic, strong) NSMutableDictionary *currentElementValue;

/// 数据模型
@property(nonatomic, strong) YYWeatherModel *weatherModel;


/// titleCity
@property(nonatomic, strong) NSString *titleCity;
/// titleBtn
@property(nonatomic, weak) UIButton *titleBtn;

/// errLabel 提示信息
@property(nonatomic, weak) UILabel *errLabel;

/// 温度条
@property(nonatomic, weak) UILabel *tempLabel;

/// weather 天气
@property(nonatomic, weak) UILabel *weatherLabel;

/// 预警信息 如雷雨大风蓝色预警
@property(nonatomic, weak) UILabel *alarmLable;

/// 更新时间
//@property(nonatomic, weak) UILabel *updateTimeLable;

@end

@implementation YYHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [SVProgressHUD setMinimumDismissTimeInterval:1000];
    
    // 数据库操作
    [self setupDB];
    
    [self setupTitle];
    
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 添加子视图
    [self setupSubview];
}

-(void)setupTitle{
    //读取上次设置的城市
    self.titleCity = [SQLOperation readLastCity][0];
    
    UIButton *titleView = [YYNoHighlightButton new];
    self.titleBtn = titleView;
    
    [titleView setImage:[UIImage imageNamed:@"location_red_24" ] forState:UIControlStateNormal];
    if (self.titleCity == nil) {
        [titleView setTitle:@"北京" forState:UIControlStateNormal];
    }else{
        [titleView setTitle:self.titleCity forState:UIControlStateNormal];
    }
    [titleView addTarget:self action:@selector(clickCity) forControlEvents:UIControlEventTouchUpInside];
    [titleView sizeToFit];
    [self.navigationItem setTitleView:titleView];
}

#pragma mark - 操作数据库
- (void)setupDB{
    // 打开数据库
    [SQLOperation openDB];
}


#pragma mark - 添加子视图
/// 添加子视图
- (void)setupSubview{
    
    //设置背景图片
    UIImageView *bkImage = [[UIImageView alloc]initWithFrame:self.view.bounds];
    bkImage.image = [UIImage imageNamed:@"bkImahe.jpg"];
    [self.view addSubview:bkImage];
//    YYLog(@"%@",NSStringFromCGRect(_scrollView.frame))
    
    //设置蒙版
    UIView *maskView = [[UIView alloc]initWithFrame:self.view.bounds];
    maskView.backgroundColor = [UIColor colorWithHue:248/255.0 saturation:211/255.0 brightness:152/255.0 alpha:0.6];
    maskView.alpha = 0;
    [self.view addSubview:maskView];
    self.maskView = maskView;
    
    // 添加scrollView
    UIScrollView *scrollV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, YYScreenW, YYScreenH-64)];
    [self.view addSubview:scrollV];
    self.scrollView = scrollV;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.delegate = self;
    //    self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //    self.scrollView.contentOffset = CGPointMake(0, 20);
    
    // 添加背景View
    UIView *bkView = [[UIView alloc]initWithFrame:_scrollView.bounds];
    [self.scrollView addSubview:bkView];
//    bkView.mj_y = -64;
    self.bkView = bkView;
    
    //设置圆环
    _progress = [XYCustomProgressView CustomProgressWithFrame:CGRectMake(0, 0, 200, 200) circleWidth:25 shadowWidth:0];
//    YYLog(@"%@",NSStringFromCGRect(self.bkView.bounds))
    _progress.center = self.bkView.center;
    _progress.mj_y -= 100;
    [self.bkView addSubview:_progress];
    
    // 改变蒙版的颜色 block
    __weak typeof(self) weakSelf = self;
    _progress.changeMaskColor = ^(pm25Level level){
        
        if (level == 0) {
            weakSelf.maskView.alpha = 0.01;
        }else {
            weakSelf.maskView.alpha = level / 10.0;
        }
        
//        YYLog(@"alpha = %f",weakSelf.maskView.alpha)
    };
    
    CGFloat space = 8;
    // 添加其他数据条
    //数据获取失败显示条
    CGFloat errY = CGRectGetMaxY(_progress.frame);
    UILabel *errLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
    errLabel.center = CGPointMake(self.bkView.center.x, errY + errLabel.mj_h / 2 + space);
//    errLabel.text = @"获取成功";
    errLabel.backgroundColor = [UIColor clearColor];
    [errLabel setTextAlignment:NSTextAlignmentCenter];
    self.errLabel = errLabel;
    [self.bkView addSubview:errLabel];
    
    // 最高温度
    CGFloat tempY = CGRectGetMaxY(errLabel.frame);
    UILabel *tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
    tempLabel.center = CGPointMake(self.bkView.center.x, tempY + tempLabel.mj_h / 2 + space);
    tempLabel.backgroundColor = [UIColor clearColor];
    [tempLabel setTextAlignment:NSTextAlignmentCenter];
    self.tempLabel = tempLabel;
    [self.bkView addSubview:tempLabel];
    // 当前天气
    CGFloat weatherY = CGRectGetMaxY(tempLabel.frame);
    UILabel *weatherLabel= [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
    weatherLabel.center = CGPointMake(self.bkView.center.x, weatherY + weatherLabel.mj_h / 2 +space);
    weatherLabel.backgroundColor = [UIColor clearColor];
    [weatherLabel setTextAlignment:NSTextAlignmentCenter];
    self.weatherLabel = weatherLabel;
    [self.bkView addSubview:weatherLabel];
    
    
    // 当前天气
//    CGFloat weatherY = CGRectGetMaxY(tempLabel.frame);
    UILabel *alarmLable= [[UILabel alloc]initWithFrame:CGRectMake(0, 0, YYScreenW, 23)];
//    weatherLabel.center = CGPointMake(self.bkView.center.x, weatherY + weatherLabel.mj_h / 2 +space);
    alarmLable.backgroundColor = [UIColor colorWithRed:255 green:127 blue:0 alpha:0.7];
    [alarmLable setTextAlignment:NSTextAlignmentCenter];
    self.alarmLable = alarmLable;
    [self.bkView addSubview:alarmLable];
    alarmLable.hidden = YES;
    
    // 添加下拉刷新
    //    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestPM25_xml)];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestPM25_xml)];
    //    header.ignoredScrollViewContentInsetTop = -10.f;
    self.scrollView.mj_header = header;
    header.automaticallyChangeAlpha = YES;
    // 设置颜色
    header.stateLabel.textColor = [UIColor whiteColor];
    header.lastUpdatedTimeLabel.textColor = [UIColor whiteColor];
}

#pragma mark - 请求数据
/// 请求 h ttp://wthrcdn.etouch.cn/WeatherApi 的数据
- (void)requestPM25_xml{
    //h ttp://wthrcdn.etouch.cn/WeatherApi?city=北京
    
    //1.创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //设置以XML的方式来解析数据
    manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
    
    UIButton *tempBtn =(UIButton *)self.navigationItem.titleView;
    NSString *btnCity = tempBtn.titleLabel.text;
    NSDictionary *dict = @{@"city":btnCity};
    
    //2.发请求
    [manager GET:@"http://wthrcdn.etouch.cn/WeatherApi" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 结束刷新
        [self.scrollView.mj_header endRefreshing];
        //        self.scrollView.contentOffset = CGPointMake(0, 0);
        
        // 得到字典
        NSDictionary *xmlDict = [NSDictionary dictionaryWithXMLParser:responseObject];
        
//        YYLog(@"dict = %@", xmlDict)
        
        // 转化成模型
        // 告诉MJExtension这个框架XMGCarGroup中的car数组属性中装的是XMGCar这个模型
        [YYForecastModel mj_setupObjectClassInArray:^NSDictionary *{
            return @{
                     @"weather" : [YYForecastWeather class],
                     @"zhishu" : [YYIndexModel class]
                     };
        }];
        
        //多级映射 @[@"date", @"date_1"]
        [YYForecastWeather mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{
                     //                    @"date"  : @"date_1",
                     @"date"   : @[@"date", @"date_1"],
                     @"high"   : @[@"high", @"high_1"],
                     @"low"    : @[@"low", @"low_1"],
                     @"day"    : @[@"day", @"day_1"],
                     @"night"  : @[@"night", @"night_1"],
                     };
        }];
    
        [YYDayModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{
                     @"fengli"      : @[@"fl_1", @"fengli"],
                     @"fengxiang"   : @[@"fx_1", @"fengxiang"],
                     @"type"        : @[@"type_1", @"type"],
                     };
        }];
        
        self.weatherModel = [YYWeatherModel mj_objectWithKeyValues:xmlDict];
        
//        YYLog(@"%@",self.weatherModel)
        
        //        [_progress setPercent:200];
        [_progress setPercent:[self.weatherModel.environment.pm25 intValue]];
        
        _currentPM25 = [self.weatherModel.environment.pm25 intValue];
        
        // 无该城市PM25数据
        if (_currentPM25 == 0) {
            self.errLabel.text = @"暂无该城市PM2.5数据";
            [SVProgressHUD showInfoWithStatus:@"暂无该城市PM2.5数据"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                
                [SVProgressHUD dismiss];
            });
//            NSTimeInterval *delay = [NSTimeInterval ];
//            [SVProgressHUD dismiss];
//            [SVProgressHUD dismissWithDelay:2000];
            
        }else{
//            NSLog(@"%@",self.weatherModel.updatetime);
            NSString *updateTime = [NSString stringWithFormat:@"%@ 发布",self.weatherModel.updatetime ];
            self.errLabel.text = updateTime;
        }
        
        // 设置高低温度
        YYForecastWeather *tempWeather = self.weatherModel.forecast.weather[0];
        self.tempLabel.text = [NSString stringWithFormat:@"最%@  最%@",tempWeather.high,tempWeather.low];
        // 设置天气情况
        if ([tempWeather.night.type isEqualToString:tempWeather.day.type]) {
            self.weatherLabel.text = [NSString stringWithFormat:@"%@",tempWeather.day.type];
        }else{
        
            self.weatherLabel.text = [NSString stringWithFormat:@"%@ 转 %@",tempWeather.day.type,tempWeather.night.type];
        }
        // 设置预警信息
        // 广州市发布雷雨大风蓝色预警，请注意防护
        if (self.weatherModel.alarm != nil) {
            NSString *alarmStr = [NSString stringWithFormat:@"%@发布%@%@预警，请注意防护！ ",self.weatherModel.city, self.weatherModel.alarm.alarmType,self.weatherModel.alarm.alarmDegree];
            self.alarmLable.text = alarmStr;
            self.alarmLable.hidden = NO;
        }else{
            self.alarmLable.hidden = YES;
        }

        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        YYLog(@"刷新失败!")

        // 结束刷新
        [self.scrollView.mj_header endRefreshing];
        // 提示
        [SVProgressHUD showInfoWithStatus:@"获取数据失败，请检查网络~"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{

            [SVProgressHUD dismiss];
        });
        //        self.scrollView.contentOffset = CGPointMake(0, 0);
//        YYLog(@"%@---",task.currentRequest.URL)
//        YYLog(@"%@---",error)
        
    }];
}


#pragma mark - 点击城市按钮
-(void)clickCity{
    YYLog(@"clickCity")
    
    YYCityViewController *vc=[[YYCityViewController alloc]init];
    
//    UIButton *tempBtn =(UIButton *)self.navigationItem.titleView;
    
//    vc.returnBlock(tempBtn.titleLabel.text);
    
//        tempBtn.titleLabel.text = cityname;

    
    [self.navigationController pushViewController:vc animated:NO];
}



#pragma mark - view 的生命周期方法

-(void)viewWillAppear:(BOOL)animated{
    // 设置导航条透明
    // UIBarMetricsDefault:必须传入这个家伙
    // 传入一个空的UIImage
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    
    // 设置导航条阴影背景
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    //    self.navigationItem.title = @"北京";
    
    // 修改返回的按钮的文字
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
//    self.navigationItem.backBarButtonItem.title = @"返回";
    
    //读取上次设置的城市
    self.titleCity = [SQLOperation readLastCity][0];
    
    if (self.titleCity == nil) {
        [self.titleBtn setTitle:@"北京" forState:UIControlStateNormal];
    }else{
        [self.titleBtn setTitle:self.titleCity forState:UIControlStateNormal];
    }
}


-(void)viewDidAppear:(BOOL)animated{

    //处理键盘
//    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)to:nil from:nil forEvent:nil];
    static NSString *city = nil;
    
    //发送网络请求
    //    [self requestPM25_xml];
    if (_weatherModel ==nil || ![city isEqualToString:self.titleCity])
    {
        city = self.titleCity;
        [self.scrollView.mj_header beginRefreshing];
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    
}


@end
